package com.jy.appmarket.screenlock.fragment;

import java.util.List;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.utils.PatternLockerUtils;
import com.jy.appmarket.screenlock.view.PatternLockerView;
import com.jy.appmarket.screenlock.view.PatternLockerView.Cell;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

//import com.apps360.toolbox.ToolBoxApp;
//import com.apps360.toolbox.tool.LockPrefs;
//import com.apps360.toolbox.utils.PatternLockerUtils;
//import com.apps360.toolbox.view.PatternLockerView;
//import com.apps360.toolbox.view.PatternLockerView.Cell;
//import com.appssuper.toolbox.R;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-2-10
 * @version 1.0
 */
public class PatternPasswordFragment extends Fragment {
	private static final String TYPE = "pattern_type";//确认密码
	public static final int CONFIRM_PSW = 1;//确认密码
	public static final int UNLOCK_PSW = 2;//主界面解锁
	private View mContentView;
	private boolean mActivityCreated = false;
	private PatternLockerView mLockPatternView;

	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private CountDownTimer mCountdownTimer = null;
	private Handler mHandler = new Handler();
	private TextView mHeadTextView;
	private Animation mShakeAnim;

	private Toast mToast;
	private Activity mActivity;
	private int mType;
	
	
	public static PatternPasswordFragment getNewInstance(int type) {
		PatternPasswordFragment fragment = new PatternPasswordFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(TYPE, type);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (mActivityCreated) {
			return;
		}
		Bundle b = getArguments();
		if (b != null) {
			mType = b.getInt(TYPE);
		}
		mActivity = this.getActivity();
		mActivityCreated = true;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (mContentView != null) { // 防止调用多次
			ViewGroup parent = (ViewGroup) mContentView.getParent();
			parent.removeView(mContentView);
			return mContentView;
		}
		mContentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_pattern_password, null);
		initView();
		return mContentView;
	}

	private void initView() {
		mContentView.findViewById(R.id.fragment_pattern_bottom_layout).setVisibility(View.VISIBLE);
		mLockPatternView = mContentView.findViewById(R.id.fragment_locker_view);
		mHeadTextView = mContentView.findViewById(R.id.fragment_pattern_hint);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		if(LockPrefs.getTouchSoundFeedback(mActivity)){
			mLockPatternView.setTactileFeedbackEnabled(true);
		}else{
			mLockPatternView.setTactileFeedbackEnabled(false);
		}
		mShakeAnim = AnimationUtils.loadAnimation(mActivity, R.anim.shake_x);
		// 紧急电话
		if(CONFIRM_PSW == mType){
			mContentView.findViewById(R.id.emergency_call_tv).setVisibility(View.INVISIBLE);
			mContentView.findViewById(R.id.delete_tv).setVisibility(View.INVISIBLE);
		}
		mContentView.findViewById(R.id.emergency_call_tv).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ComponentName comp = new ComponentName("com.android.phone", "com.android.phone.EmergencyDialer");
				Intent intent = new Intent();
				intent.setComponent(comp);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mCountdownTimer != null)
			mCountdownTimer.cancel();
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};
	protected PatternLockerView.OnPatternListener mChooseNewLockPatternListener = new PatternLockerView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<PatternLockerView.Cell> pattern) {
			if (pattern == null)
				return;
			//TODO
			if (AppMarketApplication.getLockPatternUtils().checkPattern(pattern)) {
				mLockPatternView.setDisplayMode(PatternLockerView.DisplayMode.Correct);
				mActivity.setResult(Activity.RESULT_OK);
				mActivity.finish();
			} else {
				mLockPatternView.setDisplayMode(PatternLockerView.DisplayMode.Wrong);
				if (pattern.size() >= PatternLockerUtils.MIN_PATTERN_REGISTER_FAIL) {
					mFailedPatternAttemptsSinceLastTimeout++;
					int retry = PatternLockerUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
							- mFailedPatternAttemptsSinceLastTimeout;
					if (retry >= 0) {
						if (retry == 0)
							showToast("您已5次输错密码，请30秒后再试");
						mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
						mHeadTextView.setTextColor(Color.RED);
						mHeadTextView.startAnimation(mShakeAnim);
					}

				} else {
					showToast("输入长度不够，请重试");
				}

				if (mFailedPatternAttemptsSinceLastTimeout >= PatternLockerUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
					mHandler.postDelayed(attemptLockout, 2000);
				} else {
					mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
				}
			}
		}

		public void onPatternCellAdded(List<Cell> pattern) {

		}

		private void patternInProgress() {
		}
	};

	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(PatternLockerUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
					} else {
						mHeadTextView.setText("请绘制图案密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}
				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
				}
			}.start();
		}
	};

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(mActivity, message, Toast.LENGTH_SHORT);
			mToast.setGravity(Gravity.CENTER, 0, 0);
		} else {
			mToast.setText(message);
		}
		mToast.show();
	}

}
